package com.wsd.jing.utils;

import cn.hutool.core.lang.Validator;
import cn.hutool.http.useragent.Browser;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * All rights Reserved, Designed By www.tom.com
 *
 * @author tom
 * @version 1.0.0
 * @projectName: jing
 * @packageName: com.wsd.jing.utils
 * @className: IpUtil
 * @description 解析请求客户端信息工具类
 * @createDate 2022/11/14 14:00
 * @copyright 2022/11/14 14:00 www.tom.com Inc. All rights reserved.
 */
@Slf4j
public class IpUtil {

    private static final String UNKNOWN = "unknown";
    private static final String LOCAL_IPV4 = "127.0.0.1";
    private static final String LOCAL_IPV6 = "0:0:0:0:0:0:0:1";
    private static final Integer IP_LENGTH = 15;
    private static final String  SEPARATOR = ",";
    static Searcher searcher = null;

    static {
        try {
            InputStream inputStream = new ClassPathResource("/ipdb/ip2region.xdb").getInputStream();
            byte[] cBuff = FileCopyUtils.copyToByteArray(inputStream);
            searcher = Searcher.newWithBuffer(cBuff);
        } catch (Exception e) {
            log.error("ip2region库初始化失败", e);
        }
    }

    /**
     * @param ip:ip
     * @return String
     * @author tom
     * @description ip解析坐标
     * @createDate 2022/12/6 10:50
     */
    public static String getRegion(String ip) {
        try {
            if (searcher == null) {
                log.error("ip2region对象获取失败");
                return null;
            }
            if (!Validator.isIpv4(ip)) {
                log.error("ipv4地址错误");
                return null;
            }
            if (Validator.isIpv6(ip)) {
                log.error("不支持ipv6地址解析");
                return null;
            }
            return searcher.search(ip);
        } catch (Exception e) {
            log.error("ip2region解析IP失败", e);
        }
        return null;
    }


    /**
     * @param request:
     * @return String
     * @author tom
     * @description 获取请求id地址
     * @createDate 2022/11/14 14:23
     */
    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if (LOCAL_IPV4.equals(ip) || LOCAL_IPV6.equals(ip)) {
                try {
                    ip = InetAddress.getLocalHost().getHostAddress();
                } catch (UnknownHostException e) {
                    log.error("获取本机IP失败", e);
                }
            }
        }
        // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
        if (ip != null && ip.length() > IP_LENGTH) {
            if (ip.indexOf(SEPARATOR) > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        return ip;
    }

    /**
     * @param request:
     * @return String
     * @author tom
     * @description 获取请求的浏览器名称
     * @createDate 2022/11/14 14:21
     */
    public static String getBrowserName(HttpServletRequest request) {
        String header = request.getHeader("User-Agent");
        UserAgent userAgent = UserAgentUtil.parse(header);
        Browser browser = userAgent.getBrowser();
        return browser.getName();
    }

    /**
     * @param request:
     * @return String
     * @author tom
     * @description 获取请求的浏览器版本号
     * @createDate 2022/11/14 14:21
     */
    public static String getBrowserVersion(HttpServletRequest request) {
        String header = request.getHeader("User-Agent");
        UserAgent userAgent = UserAgentUtil.parse(header);
        Browser browser = userAgent.getBrowser();
        return browser.getVersion(header);
    }

    /**
     * @param request:
     * @return String
     * @author tom
     * @description 获取请求的操作系统名称
     * @createDate 2022/11/14 14:17
     */
    public static String getOsName(HttpServletRequest request) {
        String header = request.getHeader("User-Agent");
        UserAgent userAgent = UserAgentUtil.parse(header);
        return userAgent.getOs().getName();
    }
}
